<?php


namespace app\admin\model;


use think\Model;

class AdminNode extends Model {

    protected $pk='node_id';

    //获取所有节点菜单
    public function getAll(){
        $where[] = ['is_del','=',0];
        return $this->where($where)->field('node_id as id,node_name as name,parent_id as pId')->select();
    }


    // 写入一条数据
    public function insertOne($data){
        $data['create_time'] = $time = time();
        $data['update_time'] = $time;
        $data['is_del'] = 0;
        return $this->insertGetId($data);
    }

    // 获取一条数据 根据主键
    public function getOne($node_id){

        return $this->where($this->pk,'=',$node_id)->findOrFail();
    }

    // 软删除一条数据
    public function delOne($node_id){
        $data['update_time'] = time();
        $data['is_del'] = 1;
        return $this->where($this->pk,'=',$node_id)->update($data);
    }

    // 更新一条数据
    public function updateOne($node_id,$data){
        $data['update_time'] = time();
        return $this->where($this->pk,'=',$node_id)->update($data);
    }


    //根据角色获取对应的顶级菜单和二级菜单
    public function getNodesByRoleId($role_id){

        if($role_id==1){
            $where[] = ['is_del','=',0];
            $where[] = ['parent_id','=',0];
            $myNodes = $this->where($where)->order('node_id asc')->select()->toArray();
            foreach ($myNodes as &$item){
                $childMap['parent_id'] =  $item['node_id'];
                $childMap['is_del'] = 0;
                $item['childs'] = $this->where($childMap)->order('node_id asc')->select()->toArray();
            }
        } else {
            $where[] = ['an.is_del','=',0];
            $where[] = ['arn.is_del','=',0];
            $where[] = ['arn.role_id','=',$role_id];
            $where[] = ['an.parent_id','=',0];
            $myNodes = $this->alias('an')->join('admin_role_node arn','an.node_id=arn.node_id')->where($where)->select()->toArray();
            foreach ($myNodes as &$item){
                $childMap['an.parent_id'] =  $item['node_id'];
                $childMap['an.is_del'] = 0;
                $childMap['arn.is_del'] = 0;
                $childMap['arn.role_id'] = $role_id;
                $item['childs'] = $this->alias('an')->join('admin_role_node arn','an.node_id=arn.node_id')->where($childMap)->select()->toArray();
            }
        }

        return $myNodes;
    }



}